<?php

namespace app\cms\admin\rpc\handle;

use app\cms\model\saas\saasClientServerModel;
use iflow\swoole\implement\Server\Rpc\Service;
use Swoole\Server;

class Packet extends \iflow\swoole\implement\Server\Rpc\Parsers\Packet {

    public function close(Server $server, Service $service, int $fd): bool {
        $selfClientInfo = $service -> consumer -> get($fd);

        // 变更服务状态
        $saasServerModel = new saasClientServerModel();
        $saasServerModel -> updateInfo([ 'status' => 0 ], [
            'server_ip' => $selfClientInfo['host']['tcp']['host'],
            'server_port' => $selfClientInfo['host']['tcp']['port']
        ]);

        return parent::close($server, $service, $fd); // TODO: Change the autogenerated stub
    }


    public function register(Service $service, array $data): int {
        $saasServerModel = new saasClientServerModel();

        $host = $data['host']['tcp']['host'];
        $port = $data['host']['tcp']['port'];

        $exists = $saasServerModel -> where([
            'server_ip' => $host, 'server_port' => $port
        ]) -> findOrEmpty();

        // 存在更新状态 不存在添加
        if ($exists -> isExists()) {
            $saasServerModel -> updateInfo([
                'status' => 1
            ], [ 'server_ip' => $host, 'server_port' => $port ]);
        } else {
            // 向数据库添加客户端数据
            $saasServerModel -> addSaasServer($data['name'], $host, $port,  1);
        }

        return parent::register($service, $data); // TODO: Change the autogenerated stub
    }

}